from machine import Pin
from machine import Timer
from time import sleep_ms
import time
import bluetooth

# 定义GPIO引脚
# 控制左轮电机
p18 = Pin(18, Pin.OUT)
p19 = Pin(19, Pin.OUT)
# 控制右轮电机
p00 = Pin(00, Pin.OUT)
p01 = Pin(01, Pin.OUT)

BLE_MSG = ""

class ESP32_BLE():
    #蓝牙初始化
    def __init__(self, name):
        self.led = Pin(12, Pin.OUT)     #配置LED灯引脚为输出模式
        self.timer1 = Timer(0)          #配置定时器
        self.name = name
        self.ble = bluetooth.BLE()      #创建蓝牙对象
        self.ble.active(True)           #开启蓝牙
        self.ble.config(gap_name=name)  #配置蓝牙信息
        self.disconnected()             #设置定时器中断
        self.ble.irq(self.ble_irq)      #蓝牙时间处理
        self.register()                 #配置蓝牙的uuid
        self.ble.gatts_write(self.rx, bytes(100))#默认蓝牙只接收20字节，这里更改为接收100字节
        self.advertiser()               #蓝牙广播
        self.ok = 0

    #蓝牙连接，关闭LED灯
    def connected(self):
        self.timer1.deinit()
        self.led.value(0)
        print("connected ok")

    #蓝牙未连接，LED闪烁
    def disconnected(self):        
        self.timer1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))

    #蓝牙事件处理
    def ble_irq(self, event, data):
        global BLE_MSG
        if event == 1: #_IRQ_CENTRAL_CONNECT 手机连接了此设备
            self.connected()
        elif event == 2: #_IRQ_CENTRAL_DISCONNECT 手机断开此设备
            if self.ok==0:
                self.advertiser()
                self.disconnected()
        elif event == 3: #_IRQ_GATTS_WRITE 手机发送了数据 
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip()
            
    #蓝牙UUID配置
    def register(self): 
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'

        services = (
            (
                bluetooth.UUID(service_uuid), 
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY), 
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ), 
        )

        ((self.tx, self.rx,), ) = self.ble.gatts_register_services(services)


    #蓝牙广播配置
    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name
        self.ble.gap_advertise(100, adv_data)
        print("等待连接：%s" % adv_data)
        print("\r\n")

# 车前进
def cargo():
    p18.value(0)
    p19.value(1)
    p00.value(1)
    p01.value(0)
    
# 车后退
def carback():
    p18.value(1)
    p19.value(0)
    p00.value(0)
    p01.value(1)
    
# 车左转
def carleft():
    p18.value(0)
    p19.value(1)
    p00.value(0)
    p01.value(0)
    
def carright():   
    p18.value(0)
    p19.value(0)
    p00.value(1)
    p01.value(0)
    
def carstop():
    p18.value(0)
    p19.value(0)
    p00.value(0)
    p01.value(0)

if __name__ == "__main__":
    # 车先待命
    carstop()
    
    # 配置蓝牙
    ble = ESP32_BLE("ESP32C3BLE")

    # 配置LED
    led = Pin(12, Pin.OUT)
  
    while True:
        if len(BLE_MSG)>0:
            if BLE_MSG in ["!B507","!B606","!B705","!B804","!B10;","!B20:","!B309","!B408","stop"]: #松开按键
                print(">>%s<<————停止" % BLE_MSG)
                carstop() 
            elif BLE_MSG == "!B516":  # 按下app的上键
                print(">>%s<<————向前" % BLE_MSG)
                cargo()
            elif BLE_MSG == "!B615":  # 按下app的下键
                print(">>%s<<————向后" % BLE_MSG)
                carback()
            elif BLE_MSG == "!B714":  # 按下app的左键
                print(">>%s<<————向左" % BLE_MSG)
                carleft()
            elif BLE_MSG == "!B813":  # 按下app的右键
                print(">>%s<<————向右" % BLE_MSG)
                carright()
            elif BLE_MSG == "!B11:":  # 按下app的数字1
                print(">>%s<<————大左转" % BLE_MSG)
                p18.value(0)
                p19.value(1)
                p00.value(0)
                p01.value(1)
            elif BLE_MSG == "!B219":  # 按下app的数字2
                print(">>%s<<————大右转" % BLE_MSG)
                p18.value(1)
                p19.value(0)
                p00.value(1)
                p01.value(0)
            BLE_MSG = ""
        sleep_ms(100)